package cn.qy.java.base.ch21;

/**
 * 线程中断 demo
 */
public class Ch21_05_ThreadInterrupt {
	
	static class T1 extends Thread {
		public void run() {
			try {
				// 让出指定时间的执行权
				Thread.sleep(300000);
				System.out.println("lock1 end");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		};
	}
	
	public static void main(String[] args) throws InterruptedException {
		interruptSleep();
		demo1();
		demo2();
	}
	
	// 打断 sleep
	static void interruptSleep() {
		Thread t1 = new T1();
		t1.start();
		// 确保子线程进入休眠状态
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			System.err.print("sleep interrupted" + e);
		}
		// 打断子线程，让子线程从 sleep 中返回。
		t1.interrupt();
		// 等待子线程执行完毕
		try {
			t1.join();
		} catch (InterruptedException e) {
			System.err.print("join interrupted" + e);
		}
		System.out.println("main thread stop");
	}
	
	// interrupted 使用，它会清除中断标志位
	static void demo1() throws InterruptedException {
		Thread t = new Thread() {
			public void run() {
				// 会清除中断标志位
				while(!Thread.interrupted()) {
				}
				System.out.println("demo2 thread isInterrupted: " + isInterrupted());
			};
		};
		t.start();
		t.interrupt();
		t.join();
	}
	
	// isInterrupted 使用，不会清除中断标志位
	static void demo2() throws InterruptedException {
		Thread t = new Thread() {
			public void run() {
				// 不会清除中断标志位
				while(!isInterrupted()) {
				}
				System.out.println("demo3 thread isInterrupted: " + isInterrupted());
			};
		};
		t.start();
		t.interrupt();
		t.join();
	}

}
